<?php


namespace services\buss;


use common\helpers\CommonHelper;
use common\helpers\RedisHelper;
use common\models\base\Department;
use common\models\buss\Accounts;
use common\models\buss\AccountsData;
use common\models\buss\Doctors;
use common\models\buss\Platform;
use common\models\member\Member;
use Exception;
use services\base\DepartmentService;
use services\log\LogMemberOpService;
use services\member\MemberService;
use Yii;
use common\components\Service;

class AccountsDataService extends Service
{
    /**
     * 业务数据列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getList(array $params, int $page, int $pageSize): array
    {
        $query = AccountsData::find()
            ->alias('ad')
            ->select(['ad.*', 'a.nickname account_name', 'a.use_mid', 'd.name doctor_name', 'a.department_id'])
            ->leftJoin(Accounts::tableName() . ' a', 'a.id = ad.account_id and a.status in ('.Accounts::STATUS_ENABLE.','. Accounts::STATUS_INVALID.')')
            ->leftJoin(Doctors::tableName() . ' d', 'd.id = a.doctor_id and d.status in ('.Doctors::STATUS_ENABLE.','. Doctors::STATUS_INVALID.')')
            /*->where([
                'a.project_id' => array_column(MemberService::getProjectListCondition(), 'value')
            ])*/;

        // 权限【项目、部门】
        $memberAuth = MemberService::getLoginMemberLimit();
        // 是超管直接跳过
        if ($memberAuth['super_type'] != Member::SUPER_TYPE_SUPER_ADMIN) {
            // 是否为项目管理员
            if ($memberAuth['admin_project_ids']) {
                $query->andWhere([
                    'or',
                    ['a.project_id' => $memberAuth['admin_project_ids']],// 是【一个或几个】项目管理员则查全项目数据
                    [
                        'a.department_id' => $memberAuth['all_department_ids'],
                        'a.project_id' => $memberAuth['member_project_ids'],
                        'a.use_mid' => $memberAuth['all_member_ids'],
                    ]
                ]);
            } else {
                $query->andWhere([
                    'a.department_id' => $memberAuth['all_department_ids'],
                    'a.project_id' => $memberAuth['member_project_ids'],
                    'a.use_mid' => $memberAuth['all_member_ids'],
                ]);
            }
        }

        // 开始时间
        if (isset($params['date_stime']) && $params['date_stime']) {
            $query->andWhere(['>=', 'ad.date_time', $params['date_stime']]);
        }
        // 结束时间
        if (isset($params['date_etime']) && $params['date_etime']) {
            $query->andWhere(['<=', 'ad.date_time', $params['date_etime'] . ' 23:59:59']);
        }
        // 平台
        if (isset($params['platform_id']) && $params['platform_id']) {
            $query->andWhere(['ad.platform_id' => $params['platform_id']]);
        }
        // 认证医生
        if (isset($params['doctor_id']) && $params['doctor_id']) {
            $query->andWhere(['a.doctor_id' => $params['doctor_id']]);
        }
        // 部门
        if (isset($params['department_id']) && $params['department_id']) {
            $allIds = $params['department_id'];
            $department = RedisHelper::getDepartment($params['department_id']);
            if ($department->data_level == Department::DATA_LEVEL_DEPARTMENT_ALL) {
                $childDepartmentList = DepartmentService::getChildDepartmentList($department->tree_id);
                $allIds = array_merge([$department->id], array_column($childDepartmentList, 'id'));
            }
            $query->andWhere(['a.department_id' => $allIds]);
        }

        if (isset($params['order_column']) && $params['order_column']) {
            $sort = isset($params['order_sort']) && $params['order_sort'] == 'asc' ? SORT_ASC : SORT_DESC;
            switch ($params['order_column']) {
                case 'private_sms':
                    $orderBy['ad.private_sms'] = $sort;
                    break;
                case 'clue':
                    $orderBy['ad.clue'] = $sort;
                    break;
                case 'effective_clue':
                    $orderBy['ad.effective_clue'] = $sort;
                    break;
                case 'arrive':
                    $orderBy['ad.arrive'] = $sort;
                    break;
                default :
                    break;
            }
        }
        $orderBy['ad.date_time'] = SORT_DESC;
        $orderBy['ad.id'] = SORT_DESC;
        $list = $this->getListPageRes($query, $page, $pageSize, $orderBy);
        foreach ($list['list'] as &$val) {
            $platform = $val['platform_id'] ? RedisHelper::getPlatform($val['platform_id']) : '';
            $val['platform_name'] = $platform && $platform->status != Platform::STATUS_DELETE ? $platform->name : '';
//            $department = $val['department_id'] ? RedisHelper::getDepartment($val['department_id']) : '';
//            $val['department_name'] = $department && $department->status != Department::STATUS_DELETE ? $department->department_name : '';
            $departmentName = DepartmentService::getParent($val['department_id']);
            $val['department_name'] = implode(' / ', $departmentName);
            $member = $val['use_mid'] ? RedisHelper::getMember($val['use_mid']) : '';
            $val['use_mname'] = $member && $member->status != Member::STATUS_DELETE ? $member->realname : '';
            $val['date_time'] = date('Y-m-d', strtotime($val['date_time']));
            $val['private_sms'] = CommonHelper::getNumFormat($val['private_sms']);
            $val['clue'] = CommonHelper::getNumFormat($val['clue']);
            $val['effective_clue'] = CommonHelper::getNumFormat($val['effective_clue']);
            $val['arrive'] = CommonHelper::getNumFormat($val['arrive']);
        }
        return $list;
    }

    /**
     * 更新账号粉丝数
     * @throws Exception
     */
    public function updateAccountsData(array $params): array
    {
        // 是否为编辑，编辑判断排除当前ID
        $whereId = [];
        $scenario = 'create';
        $oldData = null;
        if ($params['id']) {
            $whereId = ['!=', 'id', $params['id']];
            // 业务数据表
            $oldData = self::getData($params['id']);
            $data = AccountsData::findOne(['id' => $params['id']]);
            $scenario = 'edit';
        } else {
            $data = new AccountsData();
            // 编辑时不能更新
            $data->date_time = $params['date_time'];
            $data->platform_id = $params['platform_id'];
            $data->account_id = $params['account_id'];
        }
        // 判断名称是否存在
        $check = AccountsData::find()
            ->select(['id'])
            ->where([
                'date_time' => $params['date_time'],
                'platform_id' => $params['platform_id'],
                'account_id' => $params['account_id'],
            ])
            ->andWhere($whereId)
            ->asArray()
            ->one();
        if ($check) {
            return CommonHelper::api(422, '账号在该平台当天数据已存在');
        }

        // 录入业务数据
        $data->private_sms = $params['private_sms'] ?? '';
        $data->clue = $params['clue'] ?? '';
        $data->effective_clue = $params['effective_clue'] ?? '';
        $data->arrive = $params['arrive'] ?? '';
        $data->operation_id = Yii::$app->user->identity->member_id;
        $data->operation_name = Yii::$app->user->identity->member->realname;
        $data->saveAndCheckResult();

        LogMemberOpService::createAccountsDataLog($scenario, $data, $oldData);
        return ['id' => $data->id];
    }

    /**
     * 业务数据
     * @param int $id
     * @return AccountsData|null
     */
    public static function getData(int $id): ?AccountsData
    {
        return AccountsData::findOne($id);
    }

    /**
     * 业务数据删除
     */
    public function delete(int $dataId): int
    {
        $transaction = Yii::$app->db->beginTransaction();
        try {
            LogMemberOpService::createAccountsDataLog('delete', self::getData($dataId));
            AccountsData::deleteAll(['id' => $dataId]);
            $transaction->commit();
            return $dataId;
        } catch (\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }
}
